﻿using HtmlAgilityPack;
using Spire.Doc;
using Spire.Doc.Documents;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment;

namespace getStoryDome
{public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txt_url.Text = "http://www.biqugse.com/25885/";
            rdo_word.Checked = true;
        }

        List<string> list = new System.Collections.Generic.List< string>();

        Dictionary<string, string> itemsDic = new Dictionary<string, string>();

        #region 点击事件

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //string Url = "http://www.biqugse.com/25885/";
                string Url = txt_url.Text;
                // string Url = "http://www.biqugse.com/25885/48892853.html";

                HtmlWeb htmlWeb = new HtmlWeb();
                htmlWeb.OverrideEncoding = Encoding.UTF8;
                HtmlAgilityPack.HtmlDocument htmlDoc = htmlWeb.Load(Url);

                var totallist = htmlDoc.DocumentNode.Descendants("a").Where(t => t.InnerText.Contains("第") && t.InnerText.Contains("章")).Skip(6);
                //var kljsadn = htmlDoc.DocumentNode.Descendants("a").Where(t => t.InnerText.Contains("第1章"));
                foreach (var item in totallist)
                {
                    //  Console.WriteLine(aaaaa);
                    string pathurltring = "http://www.biqugse.com" + item.OuterHtml.Split('=')[1].Split('>')[0].Replace("\"", "");
                    list.Add(pathurltring);
                    if (itemsDic.ContainsKey(pathurltring))
                    {
                        continue;
                    }
                    itemsDic.Add(pathurltring, item.OuterHtml.Split('>')[1].Split('<')[0]);
                }
                lbl_StroyCount.Text = itemsDic.Count.ToString();
                lbl_StoryName.Text = htmlDoc.DocumentNode.SelectSingleNode("//title").InnerText;
                // var a25aaslc = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='content']");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
                //选择文件框 对象
                FolderBrowserDialog ofd = new FolderBrowserDialog();
                //打开时指定默认路径
                ofd.SelectedPath = @"C:\Users\Rocky\Desktop\新建文件夹";
            //如果用户点击确定
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //将用户选择的文件路径 显示 在文本框中
                txtFilePathOpen.Text = ofd.SelectedPath;
            }
        }

        private void btn_DownloadWord_Click(object sender, EventArgs e)
        {
            if (rdo_txt.Checked==false && rdo_word.Checked == false)
            {
                MessageBox.Show("请选择下载格式");
            }
            if (string.IsNullOrEmpty(txtFilePathOpen.Text))
            {
                MessageBox.Show("请选择要保存的文件夹地址");
            }
            if (string.IsNullOrEmpty(lbl_StoryName.Text))
            {
                MessageBox.Show("请先加载目录");
            }

            processdown();
            //var aa = itemsDic.Skip(itemsDic.Count / 20).Take(itemsDic.Count / 20);
            List<Task> TaskList = null;
            //Task.Run(() => {
            //    foreach (var t in itemsDic)
            //    {
            //        getstroryaa(t.Key, t.Value);
            //    }


            //});



            for (int i = 0; i < 100; i++)
            {
                var aaaa = itemsDic.Skip(i * itemsDic.Count / 100).Take(itemsDic.Count / 100);
                var nowTask = Task.Run(() =>
                {
                    foreach (var item in aaaa)
                    {
                        getstroryaa(item.Key, item.Value);
                    }
                });

            }



        }
        #endregion

        #region 方法

        /// <summary>
        /// 爬取当前地址页的小说类容
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private string getstroryaa(string url, string name)
        {
            string outstring = "";
            try
            {
                HtmlWeb htmlWeb = new HtmlWeb();
                htmlWeb.OverrideEncoding = Encoding.UTF8;
                HtmlAgilityPack.HtmlDocument htmlDoc = htmlWeb.Load(url);
                var a25aaslc = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='content']");

                outstring = a25aaslc.InnerHtml.Replace("<br>", "\r\n").Replace("&nbsp;", "").Trim('\r').Trim('\n').Trim('\r').Trim('\n').Trim('\r').Trim('\n');
                //name = htmlDoc.DocumentNode.SelectSingleNode("//title").ToString();
                string savePath = Path.Combine(txtFilePathOpen.Text, name + ".docx");
                string savePath2 = Path.Combine(txtFilePathOpen.Text, name + ".txt");
                if (rdo_txt.Checked == true)
                {
                    saveTxt(savePath2, name, outstring);

                }
                if (rdo_word.Checked == true)
                {
                    saveWord(savePath, name, outstring);
                }
            }
            catch (Exception)
            {

                throw;
            }
            return outstring;
        }

        /// <summary>
        /// 开线程下载
        /// </summary>
        private void processdown()
        {
            //获取当前文件夹目录个数然后除以当前的个数
            int allTotal = int.Parse(lbl_StroyCount.Text);
            string dirPath = txtFilePathOpen.Text;
            System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirPath);
            int result = GetFilesCount(dirInfo);

            Task.Run(() => {
                while (allTotal != result)
                {
                    result = GetFilesCount(dirInfo);

                    this.BeginInvoke(new Action<int,int>((int aaa,int bbb) => {

                        lbl_hadDown.Text = result.ToString();
                        lbl_downProgress.Text = ((double)result / allTotal).ToString("0.0%");
                        pb_Downprocess.Value= Convert.ToInt32(((double)result / allTotal) * 100);
                    }),1,2);

                    Thread.Sleep(1000 * 1);
                }
            });
  
            // MessageBox.Show("已下载文件个数为：" + result + "个");
        }

       /// <summary>
       /// 获得文件夹下面文件的数量
       /// </summary>
       /// <param name="dirInfo"></param>
       /// <returns></returns>
        public int GetFilesCount(DirectoryInfo dirInfo)
        {
            int totalFile = 0;
            //totalFile += dirInfo.GetFiles().Length;//获取全部文件
            if (rdo_txt.Checked == true)
            {
                totalFile += dirInfo.GetFiles("*.txt").Length;//获取某种格式

            }
            if (rdo_word.Checked == true)
            {
                totalFile += dirInfo.GetFiles("*.docx").Length;//获取某种格式
            }
          //  totalFile += dirInfo.GetFiles("*.docx").Length;//获取某种格式
            foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories())
            {
                totalFile += GetFilesCount(subdir);
            }
            return totalFile;
        }

        private void saveTxt(string savePath, string title, string outstring)
        {
            StreamWriter strmsave = new StreamWriter(savePath, false, System.Text.Encoding.Default);
            strmsave.Write(title +"\r\n"+ outstring);
            strmsave.Close();
        }
        private void saveWord(string savePath, string title,string outstring)
        {
            //创建一个Document实例

            Document doc = new Document();
            //添加一个section

            Section sec = doc.AddSection();

            //添加三个段落并写入文字

            Paragraph para1 = sec.AddParagraph();

            para1.AppendText(title);

            Paragraph para2 = sec.AddParagraph();

            para2.AppendText(outstring);


            //将第一段作为标题，设置标题格式

            ParagraphStyle style1 = new ParagraphStyle(doc);

            style1.Name = "titleStyle";

            style1.CharacterFormat.Bold = true;

            style1.CharacterFormat.TextColor = Color.Green;

            style1.CharacterFormat.FontName = "楷体";

            style1.CharacterFormat.FontSize = 18f;

            doc.Styles.Add(style1);

            para1.ApplyStyle("titleStyle");



            //设置其余两个段落的格式

            ParagraphStyle style2 = new ParagraphStyle(doc);

            style2.Name = "paraStyle";

            style2.CharacterFormat.FontName = "楷体";

            style2.CharacterFormat.FontSize = 15f;

            doc.Styles.Add(style2);

            para2.ApplyStyle("paraStyle");




            //设置三个段落的对齐方式

            para1.Format.HorizontalAlignment = HorizontalAlignment.Center;

            para2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
            //设置段首缩进

            para2.Format.FirstLineIndent = 30f;

            //设置段落之间的间距

            para1.Format.AfterSpacing = 15f;

            para2.Format.AfterSpacing = 15f;



            //保存文档

            doc.SaveToFile(savePath, FileFormat.Docx2013);
            //doc.SaveToFile("First_Word_Document.docx", FileFormat.Docx2013);



        }
        #endregion

    }
}
